#!/usr/bin/env python3
"""
使用MySQL客户端进行数据库查询的简单封装
"""

import sys
from sql_pools.mysql_config import MySQLClient


def execute_query(sql):
    """
    执行SQL查询并显示结果
    """
    # 数据库连接信息
    DB_HOST = '10.141.194.72'
    DB_PORT = 23306
    DB_USER = 'viu_root'
    DB_PASSWORD = 'myviu_4359'
    DB_NAME = 'd_cgboss_info'
    
    try:
        # 创建MySQL客户端实例
        client = MySQLClient(
            host=DB_HOST,
            port=DB_PORT,
            user=DB_USER,
            password=DB_PASSWORD,
            database=DB_NAME
        )
        
        print(f"连接到 {DB_HOST}:{DB_PORT}/{DB_NAME} 成功!")
        print(f"执行查询: {sql}")
        
        # 执行查询
        try:
            results = client.execute_query(sql)
            
            # 打印查询结果
            if not results:
                print("查询没有返回结果。")
                return
                
            print(f"查询结果 ({len(results)}行):")
            
            # 显示每行结果
            for i, row in enumerate(results):
                print(f"\n--- 第 {i+1} 行 ---")
                for key, value in row.items():
                    if value is None:
                        value = "NULL"
                    print(f"{key}: {value}")
                    
        except Exception as e:
            print(f"查询执行失败: {str(e)}")
    except Exception as e:
        print(f"数据库连接失败: {str(e)}")


# 交互式查询模式
def interactive_mode():
    """
    交互式查询模式
    """
    print("进入交互式查询模式，输入SQL语句执行查询，输入'exit'退出")
    
    while True:
        sql = input("\n请输入SQL查询 (输入'exit'退出): ")
        if sql.lower() in ('exit', 'quit', 'q'):
            break
            
        if sql.strip():
            execute_query(sql)


if __name__ == "__main__":
    # 处理命令行参数
    if len(sys.argv) > 1:
        sql = sys.argv[1]
        execute_query(sql)
    else:
        interactive_mode() 